package com.bd.scm.module.oauth2;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "Home", urlPatterns = {"/home"})
public class Home extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String server = "http://hn2n11kgkj.52http.net";
        // 如果没有本地用户会话，则向派拉请求登录信息
        if (request.getSession().getAttribute("user") == null) {
            String url = "https://portal.hascovision.com/profile/oauth2/authorize?client_id=CbtEGup0dHNO8W0B&redirect_uri="
                    + URLEncoder.encode(server + "/callback", "utf-8")
                    + "&response_type=code&target_uri="
                    + URLEncoder.encode(server + "/home", "utf-8");
            response.sendRedirect(url);
            return;
        }
        // 否则正常展示页面内容
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Home</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Home at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Home";
    }
}
